import math
import random
import pygame
import math
import sys
from settings import *


def generate_position(direction, radius_range):
    """在指定方向和半径范围内生成位置"""
    angle = math.radians(direction * 45 + random.uniform(-15, 15))
    r = random.uniform(*radius_range)
    x = WIDTH // 2 + r * math.cos(angle)
    y = HEIGHT // 2 + r * math.sin(angle)
    return x, y


def get_available_directions(direction_counts, current_directions):
    """获取可用的方向"""
    return [d for d in current_directions if direction_counts[d] < 2]


import tkinter as tk
from tkinter import ttk, messagebox


class ModeDialog:
    def __init__(self):
        self.result = None
        self.root = tk.Toplevel()
        self.root.title("模式选择")
        self.center_window(300,180)
        # 创建单选变量
        self.var_mode = tk.IntVar(value=0)

        # 构建界面
        self._create_widgets()
        self._setup_bindings()

        # 模态化窗口
        self.root.grab_set()
        self.root.wait_window()

    def _create_widgets(self):
        """创建界面组件"""
        frame = ttk.LabelFrame(self.root, text="请选择运行模式", padding=(10, 10))
        frame.pack(pady=15, padx=15, fill="both", expand=True)

        ttk.Radiobutton(frame, text="常规控体",
                        variable=self.var_mode,
                        value=0).pack(anchor="w", pady=5)
        ttk.Radiobutton(frame, text="逃课控体",
                        variable=self.var_mode,
                        value=1).pack(anchor="w", pady=5)

        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=5)

        ttk.Button(btn_frame, text="确认",
                   command=self._on_confirm).pack(side="left", padx=10)

    def _setup_bindings(self):
        """绑定窗口关闭事件"""
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _on_confirm(self):
        """确认按钮回调"""
        self.result = self.var_mode.get()
        self.root.destroy()

    def _on_close(self):
        """处理窗口关闭事件"""
        self.result = None
        self.root.destroy()

    def center_window(self, width=400, height=300):
        # 获取屏幕尺寸
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()

        # 计算居中坐标
        x = (screen_width - width) // 2
        y = (screen_height - height) // 2

        # 设置窗口位置和大小
        self.root.geometry(f"{width}x{height}+{x}+{y}")


_first = True

def create_dialog():
    global _first
    if _first:
        myroot = tk.Tk()
        myroot.withdraw()  # 隐藏主窗口
        myroot.wm_attributes("-topmost", True)  # 主窗口置顶[4](@ref)
        _first = False

def dialog_get_mode():
    """创建并返回对话框选择结果"""
    create_dialog()
    dialog = ModeDialog()
    return dialog.result if dialog.result is not None else -1

def dialog_showinfo():
    """创建并返回对话框选择结果"""
    create_dialog()
    messagebox.showinfo("使用指导", "(无法控制请手动shift切换英文输入)\r\n"
                                    "F1：    帮助\r\n"
                                    "F2：    选择控体模式\r\n"
                                    "t:     开始模拟\r\n"
                                    "WASD：  移动\r\n")


def draw_dashed_line(surface, color, start_pos, end_pos, width=1, dash_length=10):
    """绘制带长度显示的虚线（支持任意角度）"""
    # 计算线段向量
    x1, y1 = start_pos
    x2, y2 = end_pos
    dx = x2 - x1
    dy = y2 - y1
    distance = math.hypot(dx, dy)

    # 计算虚线参数
    dash_num = int(distance / dash_length)
    dx_normal = dx / distance if distance != 0 else 0
    dy_normal = dy / distance if distance != 0 else 0

    # 分段绘制虚线
    for i in range(dash_num):
        start = (x1 + dx_normal * dash_length * i,
                 y1 + dy_normal * dash_length * i)
        end = (x1 + dx_normal * dash_length * (i + 0.5),
               y1 + dy_normal * dash_length * (i + 0.5))
        pygame.draw.line(surface, color, start, end, width)

    # 返回中点坐标和线段长度
    mid_point = ((x1 + x2) / 2, (y1 + y2) / 2)
    return mid_point, int(distance * 10 / SCALE) / 10.0


def draw_text(surface, text, position, font_size=30, color=(0, 0, 0)):
    """在指定位置绘制文字"""
    font = pygame.font.SysFont('Arial', font_size)
    text_surface = font.render(f"{text:.1f}", True, color)
    text_rect = text_surface.get_rect(center=position)
    surface.blit(text_surface, text_rect)


# 使用示例
if __name__ == "__main__":

    # 初始化Pygame
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption("Dashed Line with Length")

    # 颜色定义
    WHITE = (255, 255, 255)
    BLUE = (0, 0, 255)
    BLACK = (0, 0, 0)

    # 主循环
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        screen.fill(WHITE)

        # 示例使用固定坐标点（可替换为动态输入）
        start_point = (100, 300)
        end_point = (700, 450)

        # 绘制端点标记
        pygame.draw.circle(screen, BLUE, start_point, 5)
        pygame.draw.circle(screen, BLUE, end_point, 5)

        # 绘制虚线并获取中点信息
        mid_point, length = draw_dashed_line(screen, BLUE, start_point, end_point, 5, 30)

        # 绘制长度文本
        draw_text(screen, length, mid_point)

        pygame.display.flip()

    pygame.quit()
    sys.exit()
